package com.jubaozan.c3.goods;


import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author yuanjie
 */
@EnableSwagger2
@Slf4j
@Order(1000)
@EnableConfigurationProperties(SwaggerProperties.class)
@Configuration
public class SwaggerConfiguration {


    /**
     * 定义分隔符
     */
    private static final String PACKAGE_SEP = ",";

    private final SwaggerProperties swaggerProperties;

    @Autowired
    public SwaggerConfiguration(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }

    @PostConstruct
    public void initOnce() {
        logger.info(">>>>> Swagger 配置:[{}]", swaggerProperties);
        if (StringUtils.isEmpty(swaggerProperties.getBasePackage())) {
            logger.error("No c3.swagger.base-package configured, use default com.jubaozan.service");
            swaggerProperties.setBasePackage("com.jubaozan.service");
        }
    }

    @Bean
    public Docket createRestApi() {
        // 创建API基本信息
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(basePackage(swaggerProperties.getBasePackage()))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(swaggerProperties.getVersion())
                .build();
    }

    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        final List<String> pkgs = Arrays.stream(basePackage.split(PACKAGE_SEP)).map(String::trim).collect(Collectors.toList());
        return input -> {
            // 循环判断匹配
            for (String prefix : pkgs) {
                boolean matched = Optional.fromNullable(input)
                        .transform(Class::getPackage)
                        .transform(Package::getName)
                        .transform(name -> name.startsWith(prefix))
                        .or(false);
                if (matched) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.of(input.declaringClass());
    }
}
